package com.dongjiantong.app.controller.farmrecords;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.model.FarmRecordsInspection;
import com.dongjiantong.farmrecords.service.FarmRecordsInspectionService;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 防疫中心-检验检测记录(养殖端)
 */

@Slf4j
@OpenBean
public class FarmRecordsInspectionController {

    @Reference(version = "1.0.0")
    public FarmRecordsInspectionService farmRecordsInspectionService;

    /**
     * 根据养殖场id,起止时间或者状态查询检验检测记录 (条件都可以为空,表示查询所有)
     * @param farmId  请求的养殖场id
     * @param fromDate 请求的查询开始时间
     * @param toDate   请求的查询结束时间
     * @param pageNum
     * @param pageSize
     * @param breedSecondType
     * @return  Response<PageInfo<FarmRecordsInspection>>
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsinspection.selectByFarmIdAndDate",
            paramNames = {"farmId","fromDate","toDate","pageNum","pageSize","breedSecondType"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsInspection>> selectByFarmIdAndDate(
                                                                           @RequestParam(required = false) Long farmId,
                                                                           @RequestParam(required = false) String fromDate,
                                                                           @RequestParam(required = false) String toDate,
                                                                           @RequestParam(required = false) Integer pageNum,
                                                                           @RequestParam(required = false) Integer pageSize,
                                                                           @RequestParam(required = false) Integer breedSecondType){
        if (farmRecordsInspectionService == null){
            throw new OPServerException("请检查 farmRecordsInspectionService 服务");
        }
        Map map = Maps.newHashMap();
        Long userId = UserUtil.getUserId();
        map.put("userId",userId);
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 20;
        }

        if (farmId != null){
            //如果养殖场id不为空,则根据养殖场id查询
            map.put("farm_id",farmId);
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (!Strings.isNullOrEmpty(fromDate)){
                Date startDate = sdf.parse(fromDate);
                map.put("startDate",startDate);
            }
            if (!Strings.isNullOrEmpty(toDate)){
                Date endDate = sdf.parse(toDate);
                map.put("endDate",endDate);
            }
        } catch (Exception e){
            log.error(e.getMessage());
        }

        map.put("status", FarmRecordsNumberStatus.SUBMIT.getCode());

        if (breedSecondType != null){
            map.put("breed_second_type",breedSecondType);
        }

        PageInfo<FarmRecordsInspection> farmRecordsInspectionPageInfo = farmRecordsInspectionService.selectByMap(pageNum,pageSize,map);
        return Response.ok(farmRecordsInspectionPageInfo);
    }

    /**
     * 养殖端
     * 根据提交状态分页查询列表
     * @param farmId
     * @param status
     * @return
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsinspection.selectListByStatus",
            paramNames = {"farmId","status","pageSize","pageNum"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsInspection>> selectListByStatus(@RequestParam(required = false) Long farmId,
                                                                       @RequestParam(required = false) Integer status,
                                                                       @RequestParam(required = false) Integer pageSize,
                                                                       @RequestParam(required = false) Integer pageNum){
        if (farmRecordsInspectionService == null){
            throw new OPServerException("farmRecordsDisinfectService 服务为空,请重启服务后重试");
        }
        if (farmId == null){
            throw new OPServerException("养殖场id不能为空,请检查后重试");
        }

        if (pageSize == null){
            pageSize = 20;
        }
        if (pageNum == null){
            pageNum = 1;
        }

        PageInfo<FarmRecordsInspection> productionPageInfo = farmRecordsInspectionService.selectListByStatus(pageNum,pageSize,status,farmId);

        return Response.ok(productionPageInfo);
    }

    /**
     * 根据主键id查询对应检验检测记录
     * @param id
     * @return
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsinspection.selectById",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET)
    public Response<FarmRecordsInspection> selectById(@RequestParam(required = false)Long id){
        if (id == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST,"请求id不能为空");
        }
        try {
            if (farmRecordsInspectionService == null){
                throw new OPServerException("farmRecordsInspectionService 为null,请检查");
            }
            FarmRecordsInspection farmRecordsInspection = farmRecordsInspectionService.selectByPrimaryKey(id);
            if (farmRecordsInspection == null){
                return Response.fail(HttpCode.INTERNAL_SERVER_ERROR,"查无数据");
            }
            return Response.ok(farmRecordsInspection);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }


    /**
     * 新增一条检验检测记录 (暂存状态)
     * @param farmRecordsInspection
     * @param toStatus 单据改变为状态
     * @return long 返回插入数据的id
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsinspection.createOne",
            paramNames = {"farmRecordsInspection","toStatus"},
            httpMethods = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class, RuntimeException.class})
    public Response<Map<String,Object>> createOne(@RequestBody(required = false) FarmRecordsInspection farmRecordsInspection,
                                    @RequestParam(required = false) Integer toStatus){
        if (farmRecordsInspection == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST,"请求参数对象不能为空");
        }
        if (farmRecordsInspectionService == null){
            throw new OPServerException("farmRecordsInspectionService 为null,请检查");
        }

        LoginInfo loginInfo = UserUtil.getCurrentUser();

        Long id = farmRecordsInspectionService.createOne(loginInfo,farmRecordsInspection, toStatus);

        Map<String,Object> result = Maps.newHashMap();
        result.put("receiptId",id);

        return Response.ok(result);
    }

    /**
     * 根据id或者number 更新一条单据信息
     * @param farmRecordsInspection 请求的对象
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsinspection.updateByIdOrNumber",
            paramNames = {"farmRecordsInspection","toStatus"},
            httpMethods = RequestMethod.POST)
    public Response<Object> updateByIdOrNumber(@RequestBody (required = false) FarmRecordsInspection farmRecordsInspection,
                                                @RequestParam(required = false) Integer toStatus){
        if (farmRecordsInspection == null){
            throw new OPServerException(HttpCode.BAD_REQUEST,"请求参数对象不能为空");
        }else{
            if (farmRecordsInspectionService == null){
                throw new OPServerException("farmRecordsInspectionService 为null,请检查");
            }
            if (farmRecordsInspection.getId() == null){
                throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST,HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
            }
            Integer con = farmRecordsInspectionService.updateByIdOrNumber(farmRecordsInspection,toStatus);

            Map<String,Object> map = Maps.newHashMap();
            if (con == 1) {
                map.put("updateResult","true");
            }else {
                map.put("updateResult","false");
            }

            return Response.ok(map);
        }
    }
}
